/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
    {
        unordered_map<int, int> inorderIndex;
        int n = inorder.size();
        for (int i = 0; i < n; ++i)
        {
            inorderIndex[inorder[i]] = i;
        }
        int rootId = 0;
        return buildTreeRecursive(preorder, inorderIndex, 0, n - 1, rootId);
    }

    TreeNode *buildTreeRecursive(vector<int> &preorder, unordered_map<int, int> &inorderIndex, int inorderLeftBound, int inorderRightBound, int &preorderRootId)
    {
        int rootVal = preorder[preorderRootId];
        int inorderRootId = inorderIndex[rootVal];
        TreeNode *root = new TreeNode(rootVal);
        if (inorderRootId > inorderLeftBound)
        {
            ++preorderRootId;
            root->left = buildTreeRecursive(preorder, inorderIndex, inorderLeftBound, inorderRootId - 1, preorderRootId);
        }
        if (inorderRootId < inorderRightBound)
        {
            ++preorderRootId;
            root->right = buildTreeRecursive(preorder, inorderIndex, inorderRootId + 1, inorderRightBound, preorderRootId);
        }
        return root;
    }
};